$(function() {
	var product_onSelf_datagrid = $("#product_onSelf_datagrid");
	var pay_dialog = $("#pay_dialog");
	var amountPrice = 0; //合计
	var discount = 10; //折扣
	var true_amount =0; //应收
	var totalNumber =0; //应收
	// 销售时间
	var interval2;
	var clock = document.getElementById("clock");
	interval2 = window.setInterval(function() {
		var time = new Date();
		clock.innerHTML = time.getFullYear() + "-" + (time.getMonth() + 1)
				+ "-" + time.getDate() + " " + time.getHours() + ":"
				+ time.getMinutes() + ":" + time.getSeconds();

	}, 1000);

	// layout
	// east区域,选项卡
	$('#layout').layout('add', {
		region : 'east',
		width : 350,
		title : '系统消息',
		collapsed : true,
		expandMode : 'float',
		href : '../../massage.html'
	});

	// 待售商品初始化-begin
	$("#product_onSelf_datagrid").datagrid({
		title : "code超市",
		fit : true,
		url : "/productstock/list", // 从商品库存中查
		fitColumns : true,
		pagination : true,
		striped : true,
		toolbar : "#tb",
		loadFilter: function(data){
    		if (data.rows){
    			for(var i=0;i<data.rows.length;i++){
    				data.rows[i].pId = data.rows[i].product.id;
    				data.rows[i].depotId = data.rows[i].depot.id;
    				data.rows[i].pName = data.rows[i].product.name;
    				data.rows[i].unitPrice = data.rows[i].price;
    				data.rows[i].unit = data.rows[i].product.unit;
    				data.rows[i].sn = data.rows[i].product.sn;
    			}
    			return data;
    		}
        },
		columns : [ [ {
			field : "id",
			title : "编号",
			hidden : true
		},{
			field : "storeNumber",
			title : "库存",
			hidden : true
		},{
			field : "pId",
			title : "商品",
			hidden : true
		},{
			field : "depotId",
			title : "仓库",
			hidden : true			
		},{
			field : "vipPrice",
			title : "会员价",
			hidden : true
		}, {
			field : "pName",
			title : "商品名称",
			width : 100
		}, {
			field : "sn",
			title : "商品编码",
			width : 100
		}, {
			field : "unitPrice",
			title : "售价",
			width : 100
		}, {
			field : "unit",
			title : "商品单位",
			width : 100
		} ] ],

		// 点击行(选中商品)时响应事件
		onClickRow : function(index, row) {
			var rows = $('#sale_list').datagrid("getRows");
			if(!row){
				return;
			}
			var ids = $.map(rows, function(row) {
				return row.id;
			})
			var index = $.inArray(row.id, ids);
			if (index == -1) {
				var i = 1;
				row.sum = i++;
				// 将当前商品添加到清单
				$('#sale_list').datagrid("appendRow", row);
			} else {
				var i = rows[index].sum;
				row.sum = ++i;
				//库存校验
				if(row.sum > row.storeNumber){
					$.messager.alert("温馨提示","库存不足");
					row.sum = row.sum - 1;
				}
				$('#sale_list').datagrid("deleteRow", index);
				$('#sale_list').datagrid("insertRow", {
					index : index,
					row : row
				});
			}
			//   合计 
			amountPrice = 0;
			var totalNumber = 0;
			for (var i = 0; i < rows.length; i++) {
				amountPrice += rows[i].sum * rows[i].unitPrice;
				totalNumber += rows[i].sum;
			}
			$("#amount").textbox('initValue',amountPrice);
			//商品总数
			$("#totalNumber").textbox('initValue',totalNumber);
			
			//折扣
			if(!$("#discount").val()){
				discount = 10;
			}else{
				discount = $("#discount").val();
			}
			//应收 
			true_amount = amountPrice*discount/10;
			$("#true_amount").textbox('initValue',true_amount);
			//折扣金额(差价)
			$("#totalAmount").textbox('initValue',amountPrice - true_amount);
		}
	})

	// 库存商品列表初始化-end

	// 初始化结算的dialog
	$("#pay_dialog").dialog({
		title : 'wolfcode',
		fit : true,
		buttons : "#bb",
		inline : true,
		closeable : false
	})

	// 初始化选择会员的dialog
	$("#member_dialog").dialog({
		title : '选择会员',
		height : 300,
		width : 800,
		buttons : "#bb_selectMember",
		resizable : true,
		inline : true,
		closed : true,
		modal : true
	})

	// 初始化出售商品下拉表格

	$('#sale_list').datagrid({
		title : "购物清单",
		height : 300,
		fitColumns : true,
		toolbar : "#tb_sale",
		striped : true,
		columns : [ [ {
			field : "id",
			title : "编号",
			hidden : true
		},{
			field : "storeNumber",
			title : "库存",
			hidden : true
		},{
			field : "depotId",
			title : "仓库",
			hidden : true		
		},{
			field : 'pName',
			title : '名称',
			width : 100
		}, {
			field : 'sn',
			title : '编码',
			width : 120
		}, {
			field : 'unitPrice',
			title : '单价',
			width : 100
		}, {
			field : 'sum',
			title : '数量',
			width : 60
		}, ] ]
	})

	// 初始化会员datagrid
	$('#member_datagrid').datagrid({
		fit : true,
		fitColumns : true,
		pagination : true,
		striped : true,
		singleSelect : true,
		pageList : [ 9, 29, 39, 49 ],
		pageSize : 9,
		loadFilter: function(data){
    		if (data.rows){
    			for(var i=0;i<data.rows.length;i++){
    				data.rows[i].discount = data.rows[i].level.discount;
    				data.rows[i].levelName = data.rows[i].level.levelName;
    			}
    			return data;
    		}
        },
		columns : [ [ {
			field : "discount",
			title : "折扣",
			hidden : true
		},{
			field : "id",
			title : "编号",
			hidden : true
		}, {
			field : "cardno",
			title : "会员卡号",
			width : 100
		}, {
			field : "name",
			title : "会员姓名",
			width : 100
		}, {
			field : "tel",
			title : "电话",
			width : 100
		}, {
			field : "qq",
			title : "qq",
			width : 100
		},{
			field : "levelName",
			title : "等级",
			width : 100
		}, {
			field : "availablepoint",
			title : "可用积分",
			width : 100
		}, {
			field : "balance",
			title : "卡内余额",
			width : 100
		}, {
			field : "totalpoint",
			title : "累计积分",
			width : 100,
			formatter : function(value){
				return value ? value : "无记录";
			}
		}, {
			field : "state",
			title : "状态",
			width : 100,
			formatter : function(value, row, index) {
				if (row.state) {
					return "<font style='color: green'>正常</font>";
				} else {
					return "<font style='color: red'>已挂失</font>";
				}
			}
		} ] ]

	})

	// 同一管理响应函数
	var cmdObj = {


		// 增加出售数量
		add : function() {
			// sum加一
			var row = $('#sale_list').datagrid("getSelected");
			if (!row) {
				$.messager.alert('温馨提示', '请选择选择一行后在增加');
				return;
			}
			row.sum += 1;
			//库存校验
			if(row.sum > row.storeNumber){
				$.messager.alert("温馨提示","库存不足");
				row.sum = row.sum - 1;
			}
			
			// 删除原先的行在重新添加
			var rows = $('#sale_list').datagrid("getRows");
			var ids = $.map(rows, function(row) {
				return row.id;
			})
			var index = $.inArray(row.id, ids);
			$('#sale_list').datagrid("deleteRow", index);
			$('#sale_list').datagrid("insertRow", {
				index : index,
				row : row
			});
			
			amountPrice = 0;
			var totalNumber = 0;
			for (var i = 0; i < rows.length; i++) {
				amountPrice += rows[i].sum * rows[i].unitPrice;
				totalNumber += rows[i].sum;
			}
			$("#amount").textbox('initValue',amountPrice);
			//商品总数
			$("#totalNumber").textbox('initValue',totalNumber);
			
			//折扣
			if(!$("#discount").val()){
				discount = 10;
			}else{
				discount = $("#discount").val();
			}
			//应收 
			true_amount = amountPrice*discount/10;
			$("#true_amount").textbox('initValue',true_amount);
			//折扣金额(差价)
			$("#totalAmount").textbox('initValue',amountPrice-true_amount);
		},

		// 减少出售数量
		reduce : function() {
			// sum减一
			var row = $('#sale_list').datagrid("getSelected");
			if (!row) {
				$.messager.alert('温馨提示', '请选择选择一行后在减少');
				return;
			}
			row.sum -= 1;

			// 删除原先的行在重新添加
			var rows = $('#sale_list').datagrid("getRows");
			var ids = $.map(rows, function(row) {
				return row.id;
			})
			var index = $.inArray(row.id, ids);
			$('#sale_list').datagrid("deleteRow", index);
			if (row.sum > 0) {
				$('#sale_list').datagrid("insertRow", {
					index : index,
					row : row
				});
			}
			
			amountPrice = 0;
			var totalNumber = 0;
			for (var i = 0; i < rows.length; i++) {
				amountPrice += rows[i].sum * rows[i].unitPrice;
				totalNumber += rows[i].sum;
			}
			$("#amount").textbox('initValue',amountPrice);
			//商品总数
			$("#totalNumber").textbox('initValue',totalNumber);
			
			//折扣
			if(!$("#discount").val()){
				discount = 10;
			}else{
				discount = $("#discount").val();
			}
			//应收 
			true_amount = amountPrice*discount/10;
			$("#true_amount").textbox('initValue',true_amount);
			//折扣金额(差价)
			$("#discountAmount").textbox('initValue',amountPrice-true_amount);
		},

		// 删除选中的出售商品
		remove : function() {
			var row = $('#sale_list').datagrid("getSelected");
			if (!row) {
				$.messager.alert('温馨提示', '请选择选择一行后在删除');
				return;
			}
			var rows = $('#sale_list').datagrid("getRows");
			var ids = $.map(rows, function(row) {
				return row.id;
			})

			var index = $.inArray(row.id, ids);
			$('#sale_list').datagrid("deleteRow", index);
			if(!rows){
				//清空结算数据
				$("#amount").textbox('initValue',"");
				$("#true_amount").textbox('initValue',"");
				$("#totalAmount").textbox('initValue',"");
				$("#totalNumber").textbox('initValue',"");
				$("#discountAmount").textbox('initValue',"");
			}else{
				amountPrice = 0;
				var totalNumber = 0;
				for (var i = 0; i < rows.length; i++) {
					amountPrice += rows[i].sum * rows[i].unitPrice;
					totalNumber += rows[i].sum;
				}
				$("#amount").textbox('initValue',amountPrice);
				//商品总数
				$("#totalNumber").textbox('initValue',totalNumber);
				
				//折扣
				if(!$("#discount").val()){
					discount = 10;
				}else{
					discount = $("#discount").val();
				}
				//应收 
				true_amount = amountPrice*discount/10;
				$("#true_amount").textbox('initValue',true_amount);
				//折扣金额(差价)
				$("#discountAmount").textbox('initValue',amountPrice-true_amount);
			}
				
		},

		// 改变商品数量
		number : function() {
			$.messager.prompt('修改商品数量', '请输入的数字：', function(count) {
				if (count) {
					// 将用户输入的值设置给row的sum
					var row = $('#sale_list').datagrid("getSelected");
					if (!row) {
						$.messager.alert('温馨提示', '请选择选择一行后在修改数量');
						return;
					}
					row.sum = count;
				
					// 删除原先的行在重新添加
					var rows = $('#sale_list').datagrid("getRows");
					var ids = $.map(rows, function(row) {
						return row.id;
					})
					var index = $.inArray(row.id, ids);
					$('#sale_list').datagrid("deleteRow", index);
					if (row.sum > 0) {
						$('#sale_list').datagrid("insertRow", {
							index : index,
							row : row
						});
					}
					if(rows){
						amountPrice = 0;
						var totalNumber = 0;
						for (var i = 0; i < rows.length; i++) {
							amountPrice += rows[i].sum * rows[i].unitPrice;
							totalNumber += rows[i].sum;
						}
						$("#amount").textbox('initValue',amountPrice);
						//商品总数
						$("#totalNumber").textbox('initValue',totalNumber);
						
						//折扣
						if(!$("#discount").val()){
							discount = 10;
						}else{
							discount = $("#discount").val();
						}
						//应收 
						true_amount = amountPrice*discount/10;
						$("#true_amount").textbox('initValue',true_amount);
						//折扣金额(差价)
						$("#discountAmount").textbox('initValue',amountPrice-true_amount);              
					}else{
						//清空结算数据
						$("#amount").textbox('initValue',"");
						$("#true_amount").textbox('initValue',"");
						$("#totalAmount").textbox('initValue',"");
						$("#totalNumber").textbox('initValue',"");
						$("#discountAmount").textbox('initValue',"");
					}
				}
			});
		},

		// 顶部工具栏:高级查询
		query : function() {
			// 获取查询参数
			var kw = $("#keyword").textbox("getValue");
			// 表格加载时顺带一起传递查询参数
			emp_datagrid.datagrid("load", {
				keyword : kw
			});
		},
		// 选择会员
		loadMemberList : function() {
			var memberGrid = $('#member_datagrid').datagrid('options');
			memberGrid.url = "/member/list";
			$("#member_datagrid").datagrid('reload');
			$("#member_dialog").dialog('open')
		},
		
		// 结算
		payForm : function() {
			// 是否有row
			var rows = $('#sale_list').datagrid("getRows");
			if (!rows) {
				$.messager.alert("温馨提示", "请选择要结算的商品");
				return;
			}
			
			$.messager.confirm('确认','您确认想要结算当前商品吗？',function(r){    
			    if (r){    
			        //结算(保存 销售帐 stockOutcomeBill/save)
			    	$('#pay_form').form('submit', {
			    		url: '/stockOutcomeBill/save',
			    		//提交额外的参数
			    		onSubmit: function(param){
			    			param["paykind"] = $("#paykind").combobox("getValue");
			    			//提交订单明细
			    			var rows = $('#sale_list').datagrid("getRows");
			    			if(rows){
			    				param["paykind"] = $("#paykind").combobox("getValue");
			    				param["depot.id"] = rows[0].depotId;
			    				for (var i = 0; i < rows.length; i++) {
			    					param["items["+ i +"].product.id"] = rows[i].product.id;
			    					param["items["+ i +"].salePrice"] = rows[i].unitPrice;
			    					param["items["+ i +"].number"] = rows[i].sum;
			    					param["items["+ i +"].discount"] = $("#discount").textbox("getValue");
			    				}
			    			}
			    
			    		},
			    		success: function(data){
			    			data = $.parseJSON(data);
			    			if(data.success){
			    				$.messager.alert("温心提示","结算成功");
			    			}else{
			    				$.messager.alert("温馨提示",data.errorMsg);
			    			}
			    		}
			    	});

			    }    
			});
		
		},


		// 选择会员: 选择
		select : function() {
			// 是否选中row
			var row = $('#member_datagrid').datagrid("getSelected");
			if (!row) {
				$.messager.alert("温馨提示", "请选择要编辑的数据");
				return;
			}
			var rows = $('#sale_list').datagrid("getRows");
			
			// 清空上次操作的数据
			$("#pay_form").form("clear");
			
			// 回显选中的行			
			row["member.id"] = row.id;
			
			$("#pay_form").form("load", row);
			
			//   合计 
	
			amountPrice = 0;
			totalNumber = 0;
			for (var i = 0; i < rows.length; i++) {
				amountPrice += rows[i].sum * rows[i].unitPrice;
				totalNumber += rows[i].sum;
			}
			$("#amount").textbox('initValue',amountPrice);
			//商品总数
			$("#totalNumber").textbox('initValue',totalNumber);
			
			//折扣
			if(!$("#discount").val()){
				discount = 10;
			}else{
				discount = $("#discount").val();
			}
			//应收 
			true_amount = amountPrice*discount/10;
			$("#true_amount").textbox('initValue',true_amount);
			//折扣金额(差价)
			$("#discountAmount").textbox('initValue',amountPrice-true_amount);
			// 关闭当前对话框
			$("#member_dialog").dialog('close');
		},

		// 取消
		cancel : function() {
			$("#member_dialog").dialog('close')
		}

	} // end


	// 调用cmdObj
	$("a[data-cmd]").click(function() {
		var cmd = $(this).data('cmd');
		cmdObj[cmd]();
	})

})
